<?php
namespace Admin\Controller;

use Utuo\BackgroundController;

class ProductBrandController extends BackgroundController {
	
	private $classId = 0;
			
	public function _initialize() {
		$this->classId = I('cls_id', 0, "intval");
		$this->setControllerTitle("产品品牌管理");
		$this->setActionTitle(array(
			'index' => '品牌列表',
			'add' => '添加品牌',
			'modify' => "修改品牌",
			'recycle' => "回收站"
		), '', 'cls_id='.$this->classId);
		$this->setActionNav("index,add,recycle");
		$this->assign("classId", $this->classId);
	}
	
	public function indexAction() {
		$this->getList( 0 );
	}
	
	public function recycleAction() {
		$this->getList( 1 );
	}
	
	private function getList( $is_deleted = 0 ) {
		$page = $this->getPage();
		$condition = array(
			'is_deleted' => $is_deleted,
		);
		$this->classId and $condition['class_id'] = $this->classId;
		$m = M("ProductBrand")->where($condition);
		$n = clone $m;
		$totalRows = $n->count();
		$productBrandLists = $m->page( $page )->limit( $this->pageSize )->select();
		$this->showPage($totalRows,  $this->pageSize);
		$this->assign("productBrandLists", $productBrandLists);
		$this->display();
	}
	
	// 修改
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$model = CONTROLLER_NAME;
		$config = D($model)->find( $id );
		$this->assign(lcfirst($model), $config);
		$this->display("save");
	}
	
	// 提交修改菜单
	public function submitPost() {
		$model = D("ProductBrand");
		if ($model->isCreated or $model->create()) {
			if (empty($_REQUEST['id'])) {
				unset($model->id);
				if ($model->add()) {
					$this->ajaxSuccess("添加成功！");
				} else {
					$this->ajaxError("添加失败！");
				}
			} else {
				if (false !== $model->save()) {
					$this->ajaxSuccess("修改成功！");
				} else {
					$this->ajaxError("修改失败！");
				}
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
	// 异步获得品牌列表
	public function getBrandListAction() {
		$name = I("name", "");
		$productBrandList = M("ProductBrand")->where(array('name'=>array('like', "%$name%")))->field("id,name")->limit(20)->select();
		$this->ajaxSuccess("", $productBrandList);
	}
	
}